package models

import (
	"fmt"
	"reflect"
	"strings"
	"time"
)

type Book struct {
	Id          int
	Name        string
	Info        string
	CreatedTime time.Time
}

func GetBookById(id int, fields []string) (*map[string]interface{}, error) {
	log.Debug("models.GetBookById input params:{id:%v ,fields:%v}", id, fields)
	db, err := openDB()
	if err != nil {
		return nil, err
	}
	defer closeDB(db)
	var sql = "SELECT * FROM book WHERE id=$1"
	var defaultFields = []string{"Id", "Name", "Info", "CreatedTime"}
	if len(fields) > 0 {
		sql = fmt.Sprintf("SELECT %v FROM book WHERE id=$1", strings.ToLower(strings.Join(fields, ",")))
		defaultFields = fields
	}

	log.Debug("models.GetBookById sql: %v", sql)

	row := db.QueryRow(sql, id)

	var fieldsValues []interface{}
	for range defaultFields {
		var fieldValue interface{}
		fieldsValues = append(fieldsValues, &fieldValue)
	}
	err = row.Scan(fieldsValues...)
	if err != nil {
		return nil, err
	}

	var m = make(map[string]interface{})
	for k, v := range defaultFields {
		val := reflect.Indirect(reflect.ValueOf(fieldsValues[k])).Elem()
		switch val.Kind() {
		case reflect.Int64:
			m[v] = val.Int()
		case reflect.Slice:
			m[v] = string(val.Bytes())
		case reflect.Struct:
			m[v] = val.Interface().(time.Time).Format("2006-01-02 15:04:05.000 -0700")
		}
	}
	log.Debug("models.GetBookById return:{err:%v ,map:%v}", err, m)
	return &m, nil
}

func CreateBook() error {
	db, err := openDB()
	if err != nil {
		return err
	}
	defer closeDB(db)
	sql := "INSERT INTO book (name,info,created_time) VALUES ($1,$2,$3)"
	b := &Book{Name: "追风筝的人", Info: "追风筝的人的简介"}
	_, err = db.Exec(sql, b.Name, b.Info, time.Now())
	//_, err = db.Exec(sql, book.Name, book.Info)
	fmt.Println("c_err: ", err)
	if err != nil {
		return err
	}
	return nil
}
